import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 东莞呵呵
 * Date:2022-04-05
 * Time:15:44
 */
public class MyArrayList {
    public int[] elem;
    public int useSize;

    public MyArrayList() {
        this.elem = new int[10];
    }

    //打印顺序表
    public void printArrayList() {
        for (int i = 0; i < useSize; i++) {
            System.out.println(elem[i]);
        }
    }

    //添加元素
    public void add(int pos, int data) {
        //1.判断是否满
        if (pos == this.elem.length) {
            Arrays.copyOf(this.elem, this.elem.length * 2);
        }
        //2.转移数据
        if (pos < 0 || pos > this.useSize) {
            System.out.println("输入非法，");
            return;
        } else {
            for (int i = this.useSize - 1; i >= pos; i--) {
                this.elem[i + 1] = this.elem[i];
            }
            this.elem[pos] = data;
            //3.有效长的+1
            this.useSize++;
        }
    }

    // 查找某个元素对应的位置
    public int search(int toFind) {
        for (int i = 0; i < this.useSize; i++) {
            if (toFind == this.elem[i]) {
                return i;
            }
        }
        return -1;
    }

    // 获取 pos 位置的元素
    public int getPos(int pos) {
        if (pos < 0 || pos >= this.useSize) {
            if (this.useSize == 0) {
                System.out.println("顺序表为空");
                return -1;
            }
            System.out.println("坐标非法");
            return -1;
        } else {
            return this.elem[pos];
        }
    }

    // 给 pos 位置的元素设为 value
    public void setPos(int pos, int value) {
        if (pos < 0 || pos >= this.useSize) {
            System.out.println("坐标非法");
            if (this.useSize == 0) {
                System.out.println("顺序表为空");
                return;
            }
            return;
        } else {
            this.elem[pos] = value;
        }
    }

    //删除第一次出现的关键字key
    public void remove(int toRemove) {
        int ret = this.search(toRemove);
        if (ret < 0) {
            System.out.println("没有该元素");
        } else {
            for (int i = ret; i < this.useSize - 1; i++) {
                this.elem[i] = this.elem[i + 1];
            }
            //this.elem[i]=null;如果存放的是对象则要制空。方便内存回收
            this.useSize--;
        }
    }
}
